package com.yxy.controller.service;

import com.google.common.collect.Maps;
import com.yxy.common.BaseController;
import com.yxy.common.Const;
import com.yxy.controller.app.UserController;
import com.yxy.dto.UserModel;
import com.yxy.common.ServerResponse;
import com.yxy.entity.User;
import com.yxy.service.IFileService;
import com.yxy.service.IUserService;
import com.yxy.util.DateUtils;
import com.yxy.util.MD5Util;
import com.yxy.util.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/service/admin/")
public class AdminController extends BaseController {

    public Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private IUserService iUserService;

    @Autowired
    private IFileService iFileService;

    @RequestMapping(value = "login.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<UserModel> login(@RequestBody User entity, HttpSession session, HttpServletRequest request,HttpServletResponse response) {


        String sessionCode = session.getAttribute("code").toString();
        if (entity.getCode()!=null &&!entity.getCode().toUpperCase().equals(sessionCode)){
            return ServerResponse.createByErrorMessage("验证码错误");
        }
        String md5password = MD5Util.MD5EncodeUtf8(entity.getPassword());
        System.out.println(md5password);
        entity.setPassword(md5password);
        User user = iUserService.AdminLogin(entity);
        if(user==null){
            return ServerResponse.createByErrorMessage("密码错误");
        }
        if(user.getRole()!=null && user.getRole()>Const.Role.ROLE_CUSTOMER){
            user.setLoginIp(UserController.getIpAddress(request));
            iUserService.updateByPrimaryKey(user);
            UserModel userModel = entityToModel(user);
            userModel.setPassword(null);//置空密码
            session.setAttribute(Const.ADMIN_USER,user);
            return ServerResponse.createBySuccess("登陆成功",userModel);
        }
        return ServerResponse.createByErrorMessage("权限错误");
    }

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index1(HttpServletRequest request, HttpServletResponse response) throws IOException {

        response.addHeader("cache-control","no-cache");
        response.addHeader("pragma","no-cache");
        response.addHeader("Expires","0");
        User user = (User) request.getSession().getAttribute("admin");
        if (user == null) {
            //session中没有用户信息就重登
            return "redirect:/loginPage";
        }
        System.out.println("登录名:" + user.getPhone());
        return "index";
    }

    @RequestMapping("loginOut")
    public String loginOut(HttpSession session) {

        session.invalidate();
        logger.info("用户退出系统");

        return "redirect:/loginPage";
    }

   @RequestMapping(value = "getAllUsers", method = RequestMethod.GET)
   @ResponseBody
   public List<UserModel> getAllUsers(){
        List<UserModel> userModels= new ArrayList<UserModel>();
        List<User> userList = iUserService.selectAll();
        if(userList!=null && userList.size()>0){
            for (User user:userList) {
                user.setPassword(null);//置空密码，安全性
                UserModel userModel = entityToModel(user);
                userModels.add(userModel);
            }
        }
        return userModels;
   }

    @RequestMapping(value = "getUserInfo", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<User> getUserInfo(HttpSession session){
        User user = (User) session.getAttribute(Const.ADMIN_USER);
        if (user != null){
            return ServerResponse.createBySuccess(user);
        }
        return ServerResponse.createByErrorMessage("用户未登陆，无法获取当前用户的信息");
    }

    //更换头像
    @RequestMapping("uploadface")
    @ResponseBody
    public ServerResponse upload(HttpSession session, @RequestParam(value = "userFace",required = false) MultipartFile file, HttpServletRequest request,String oldFileName){

            User user = (User) session.getAttribute(Const.ADMIN_USER);
            if (user!=null){
                String path = request.getSession().getServletContext().getRealPath("upload");
                String targetFileName = iFileService.upload(file,path,oldFileName,Const.IMG_USERFACE);
                String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;

                Map fileMap = Maps.newHashMap();
                fileMap.put("uri",targetFileName);
                fileMap.put("url",url);
                user.setUserFace(targetFileName);
                setTemplateDateAndUser(user,request);
                iUserService.updateByPrimaryKey(user);
                return ServerResponse.createBySuccess(fileMap);
            }
            return ServerResponse.createByErrorMessage("用户未登录");

    }
    //删除用户
    @RequestMapping("delete")
    @ResponseBody
    public ServerResponse delete(Integer id){
        if(iUserService.deleteUserById(id)){
            return ServerResponse.createBySuccessMessage("用户删除成功");
        }
        return ServerResponse.createByErrorMessage("操作失败，请重试！");
    }
    //修改用户

    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<UserModel> update(@RequestBody UserModel userModel,HttpServletRequest request){
        User user = modelToEntity(userModel);

        String md5Pwd = MD5Util.MD5EncodeUtf8("123456");
        user.setPassword(md5Pwd);//初始密码
        setTemplateDateAndUser(user,request);
        if(iUserService.updateByPrimaryKey(user)){
            return ServerResponse.createBySuccessMessage("用户更新成功!");
        }
        return ServerResponse.createByErrorMessage("操作失败,请重试!");
    }

    //查询用户
    @RequestMapping("selectUser")
    @ResponseBody
    public ServerResponse selectUser(Integer id){
        User user = iUserService.selectUserById(id);
        if (user!=null){
            UserModel model = entityToModel(user);
            return ServerResponse.createBySuccess("查询成功",model);
        }
        return ServerResponse.createByErrorMessage("操作失败，请重试！");
    }

    //添加用户
    @RequestMapping(value = "addUser", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<UserModel> cerate(@RequestBody UserModel userModel,HttpServletRequest request){

        User user = modelToEntity(userModel);

        boolean validPhone = iUserService.checkValid(user.getPhone(),"phone");
        if(validPhone){
            return ServerResponse.createByErrorMessage("手机号已被注册");
        }
        //邮箱验证
        if(user.getEmail()!=null){
            boolean validEmail = iUserService.checkValid(user.getEmail(),"email");
            if(validEmail){
                return ServerResponse.createByErrorMessage("邮箱已被注册");
            }
        }
        String md5Pwd = MD5Util.MD5EncodeUtf8("123456");
        user.setPassword(md5Pwd);
        setTemplateDateAndUser(user,request);
        if(iUserService.register(user)>0){
            return ServerResponse.createBySuccessMessage("添加成功");
        }
        return ServerResponse.createByErrorMessage("操作失败，请重试！");
    }
    //查询用户
    @RequestMapping(value = "query", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse query(String phone){
        User user = new User();
        user.setPhone(phone);
        List<User> userList = iUserService.findLikeList(user);
        List<UserModel> userModels =new ArrayList<UserModel>();
        if (userList!=null && userList.size()>0){
            for (User u:userList) {
                UserModel model = entityToModel(u);
                userModels.add(model);
            }

        }
        return ServerResponse.createBySuccess("查询成功",userModels);
    }

    // 修改密码
    @RequestMapping(value = "reset_password",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> resetPassword(HttpSession session,String passwordOld,String passwordNew,HttpServletRequest request){
        User user = (User)session.getAttribute(Const.ADMIN_USER);
        if(user == null){
            return ServerResponse.createByErrorMessage("用户未登录");
        }
        setTemplateDateAndUser(user,request);
        return iUserService.resetPassword(passwordOld,passwordNew,user);
    }


    /**
     * 统一设置 Date 和 修改用户
     *
     * @param entity
     */
    public void setTemplateDateAndUser(User entity, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(Const.ADMIN_USER);

        if (entity == null) {
            logger.error("ERR:Date set error.");
            return;
        }
        if (entity.getId() == null && entity.getCreateTime() == null) {
            //如果id为空， 就是新建
            entity.setCreateTime(new Date());
            entity.setCreateBy(user.getNickname());
        } else {

            if (entity.getUpdateTime() == null) {
                entity.setUpdateTime(new Date());
            }
            if (entity.getUpdateBy() == null ) {
                entity.setUpdateBy(user.getPhone());
            }
        }
    }



    /**
     * 将entity转换为前端model
     * @param entity
     * @return
     * @throws Exception
     */
    public UserModel entityToModel(User entity)  {
        UserModel model = new UserModel();
        if(entity.getId()!=null){
            model.setId(String.valueOf(entity.getId()));
        }
        if (entity.getUsername()!=null){
            model.setUsername(entity.getUsername());
        }
        if(entity.getPassword()!= null){
            model.setPassword("不可见");
        }
        if(entity.getPhone()!=null){
            model.setPhone(entity.getPhone());
        }
        if(entity.getEmail()!=null){
            model.setEmail(entity.getEmail());
        }
        if(entity.getCreateTime()!=null){
            model.setCreateTime(DateUtils.formatDateTime(entity.getCreateTime()));
        }
        if(entity.getUpdateTime()!=null){
            model.setUpdateTime(DateUtils.formatDateTime(entity.getUpdateTime()));
        }
        if(entity.getCreateBy()!=null){
            model.setCreateBy(entity.getCreateBy());
        }
        if(entity.getUpdateBy()!=null){
            model.setUpdateBy(entity.getUpdateBy());
        }
        if(entity.getLoginIp()!=null){
            model.setLoginIp(String.valueOf(entity.getLoginIp()));
        }else {
            model.setLoginIp("暂无登录");
        }
        if(entity.getRole()!=null){
            model.setRole(String.valueOf(entity.getRole()));
            if(entity.getRole()== Const.Role.ROLE_CUSTOMER){
                model.setRoleText(Const.RoleText.ROLE_CUSTOMER_TEXT);
            }
            if(entity.getRole()==Const.Role.ROLE_ADMIN){
                model.setRoleText(Const.RoleText.ROLE_ADMIN_TEXT);
            }
            if(entity.getRole()==Const.Role.ROLE_SUPPER_ADMIN){
                model.setRoleText(Const.RoleText.ROLE_SUPPER_ADMIN_TEXT);
            }
        }
        if(entity.getSex()!=null){
            model.setSex(String.valueOf(entity.getSex()));
            if(entity.getSex()==Const.Sex.SEX_MALE){
                model.setSexText(Const.SexText.SEX_MALE_Text);
            }
            if(entity.getSex()==Const.Sex.SEX_FAMALE){
                model.setSexText(Const.SexText.SEX_FAMALE_Text);
            }
        }
        if(entity.getStatus()!=null){
            model.setStatus(String.valueOf(entity.getStatus()));
            if(entity.getStatus()==Const.Status.STATUS_ACTIVATION){
                model.setStatusText(Const.StatusText.STATUS_ACTIVATION_Text);
            }
            if(entity.getStatus()==Const.Status.STATUS_FROZEN){
                model.setStatusText(Const.StatusText.SSTATUS_FROZEN_Text);
            }
        }
        if(entity.getNickname()!=null){
            model.setNickname(entity.getNickname());
        }
        if(entity.getUserFace()!=null){
            model.setUserFace(String.valueOf(entity.getUserFace()));
        }
        return model;
    }

    /**
     * 将前端model转换成entity
     * @param model
     * @return
     */
    public User modelToEntity(UserModel model) {
        User entity = new User();
        if(model.getId()!=null){
            entity.setId(Integer.parseInt(model.getId()));
        }
        if(model.getUsername()!= null){
            entity.setUsername(String.valueOf(model.getUsername()));
        }
        if(model.getNickname()!=null){
            entity.setNickname(String.valueOf(model.getNickname()));
        }
        if(model.getSex()!= null){
            entity.setSex(Integer.parseInt(model.getSex()));
        }
        if(model.getLoginIp()!= null){
            entity.setLoginIp(String.valueOf(model.getLoginIp()));
        }
        if(model.getPhone()!=null){
            entity.setPhone(String.valueOf(model.getPhone()));
        }
        if(model.getEmail()!=null){
            entity.setEmail(String.valueOf(model.getEmail()));
        }
        if(model.getRole() != null){
            entity.setRole(Integer.parseInt(model.getRole()));
        }
        if(model.getPassword()!=null){
            entity.setPassword(String.valueOf(model.getPassword()));
        }
        if(model.getStatus()!=null){
            entity.setStatus(Integer.parseInt(model.getStatus()));
        }
        if(model.getNickname()!=null){
            entity.setNickname(String.valueOf(model.getNickname()));
        }else {
            entity.setNickname(model.getPhone());//注册，昵称默认为手机号
        }
        return entity;
    }
}
